<template>
  <div class="app-container">
    <el-button type="primary" icon="el-icon-search" @click="searchAction" style="margin: 10px 10px">查询</el-button>
    <!-- 隐藏的日期选择器 -->
    <el-date-picker
      v-model="selectedDate"
      type="date"
      placeholder="选择日期"
      value-format="yyyy-MM-dd"
      :style="datePickerStyle"
      ref="datePicker"
      @change="handleDateChange"
      @blur="hideDatePicker"
      popper-class="custom-date-picker-popup">
    </el-date-picker>

    <el-table border="border"
              v-loading="loading"
              :data="tableData" style="width: 100%">
      <el-table-column align="center" type="index" label="序号" width="50"></el-table-column>
      <el-table-column prop="uid" label="文书id" width="300"></el-table-column>
      <el-table-column prop="" label="文书地址">
        <template slot-scope="{row}">
          <a v-if="row.documentUrl" :href="row.documentUrl" target="_blank">查看文书</a>
          <span v-else>无</span>
        </template>
      </el-table-column>
      <el-table-column prop="documentCatalogCode" label="文书类型"></el-table-column>
      <el-table-column prop="A058LASPB" label="文书类型"></el-table-column>
      <el-table-column prop="prop" label="操作" align="center" fixed="right" width="120">
        <template slot-scope="{row,$index}">
          <el-button @click="showDialogAction(row)" type="primary" icon="el-icon-edit" circle></el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-pagination
      style="margin-top: 20px;text-align: center"
      @current-change="handleCurrentChange"
      :current-page.sync="pageDto.pageNum"
      :page-size="pageDto.pageSize"
      :page-count="7"
      background
      layout="total, prev, pager, next,jumper"
      :total="total">
    </el-pagination>

    <el-drawer
      size="100%"
      :with-header="false"
      direction="rtl"
      :show-close="true"
      :destroy-on-close="true"
      :before-close="handleClose"
      :visible.sync="dialogFormVisible"
      :modal="false"
      :modal-append-to-body="false">

      <!-- 底部按钮区域 -->
      <div class="drawer-header">
        <span>{{ title }}</span>
      </div>

      <!-- 抽屉主要内容区域 -->
      <div class="drawer-content">
        <div class="drawer-content-left">
          <!-- 左侧内容 -->
        </div>
        <div class="drawer-content-right">
          <div class="drawer-body">
            <div ref="contentContainer" v-html="contentHtml" @click="handleContentClick"></div>
          </div>
        </div>
      </div>

      <!-- 底部按钮区域 -->
      <div class="drawer-footer">
        <el-button size="medium" class="btn-default btn-cancel" style="background: #FFFFFF" @click="cancelAction">取
          消
        </el-button>
        <el-button size="medium" class="btn-default" :loading="loading" type="primary" @click="addAction">提 交
        </el-button>
      </div>
    </el-drawer>
  </div>
</template>

<script>
import * as api from './api'
import * as docTemplateApi from './../doctemplate/api'
import {generatePdf} from "./api";

export default {
  name: 'DocList',
  components: {},
  data() {
    return {
      value1: '',
      pageDto: {
        pageNum: 1,
        pageSize: 10
      },
      total: 0,
      tableData: [],
      loading: false,
      dialogFormVisible: false,
      form: {},
      title: "制作文书",
      contentHtml: "",
      dataMap: {},
      selectedDate: '',
      // 日期选择器定位和显示控制
      datePickerStyle: {
        position: 'fixed',
        top: '-9999px',
        left: '-9999px',
        width: '0',
        height: '0',
        opacity: '0',
        pointerEvents: 'none'
      },
      isDatePickerVisible: false,
      currentDayIconElement: null
    }
  },
  mounted() {
    this.pageAction()
    this.initEventDelegation();
  },
  beforeDestroy() {
    document.removeEventListener('click', this.handleDocumentClick);
  },
  methods: {
    // 初始化事件委托
    initEventDelegation() {
      // console.log('初始化事件委托');
      document.addEventListener('click', this.handleDocumentClick);
    },

    // 处理文档点击事件
    handleDocumentClick(event) {
      const target = event.target;
      const dayIconElement = this.findDayIconElement(target);

      if (dayIconElement) {
        console.log('事件委托捕获到 day-control 点击:', dayIconElement);
        event.preventDefault();
        event.stopPropagation();
        this.openDatePicker(dayIconElement);
      } else if (this.isDatePickerVisible && !this.isDatePickerElement(target)) {
        // 点击其他区域隐藏日期选择器
        this.hideDatePicker();
      }
    },

    // 处理抽屉内容的点击事件
    handleContentClick(event) {
      const target = event.target;
      const dayIconElement = this.findDayIconElement(target);

      if (dayIconElement) {
        // console.log('抽屉内容中点击 day-control:', dayIconElement);
        event.preventDefault();
        event.stopPropagation();
        this.openDatePicker(dayIconElement);
      }
    },

    // 查找 day-control 元素
    findDayIconElement(element) {
      if (element && element.classList && element.classList.contains('day-control')) {
        return element;
      }

      let currentElement = element;
      while (currentElement && currentElement !== document.body) {
        if (currentElement.classList && currentElement.classList.contains('day-control')) {
          return currentElement;
        }
        currentElement = currentElement.parentElement;
      }
      return null;
    },

    // 检查是否是日期选择器相关元素
    isDatePickerElement(element) {
      let currentElement = element;
      while (currentElement && currentElement !== document.body) {
        if (currentElement.classList &&
          (currentElement.classList.contains('el-date-picker') ||
            currentElement.classList.contains('el-picker-panel') ||
            currentElement === this.$refs.datePicker?.$el)) {
          return true;
        }
        currentElement = currentElement.parentElement;
      }
      return false;
    },

    // 打开日期选择器
    openDatePicker(dayIconElement) {
      // console.log('打开日期选择器，触发元素:', dayIconElement);
      this.currentDayIconElement = dayIconElement;
      this.positionDatePicker(dayIconElement);

      this.$nextTick(() => {
        this.showDatePicker();
      });
    },

    // 定位日期选择器
    positionDatePicker(dayIconElement) {
      const rect = dayIconElement.getBoundingClientRect();
      const scrollTop = window.pageYOffset || document.documentElement.scrollTop;
      const scrollLeft = window.pageXOffset || document.documentElement.scrollLeft;
      const top = rect.bottom + scrollTop;
      const left = rect.left + scrollLeft;
      this.datePickerStyle = {
        position: 'fixed',
        top: `${top}px`,
        left: `${left}px`,
        width: '1px',
        height: '1px',
        opacity: '0.01',
        zIndex: '99999',
        pointerEvents: 'auto'
      };
      // console.log('日期选择器定位到:', {top, left});
    },

    // 显示日期选择器
    showDatePicker() {
      if (!this.$refs.datePicker) {
        console.error('日期选择器引用不存在');
        return;
      }

      try {
        this.isDatePickerVisible = true;

        // 方法1：直接调用 focus 方法
        setTimeout(() => {
          const datePicker = this.$refs.datePicker;
          if (datePicker && datePicker.focus) {
            datePicker.focus();
          }

          // 方法2：触发输入框点击
          const inputEl = datePicker.$el?.querySelector('input');
          if (inputEl) {
            inputEl.click();
            // console.log('日期选择器输入框被点击');
          }
        }, 50);

      } catch (error) {
        console.error('显示日期选择器失败:', error);
        this.hideDatePicker();
      }
    },

    // 隐藏日期选择器
    hideDatePicker() {
      this.isDatePickerVisible = false;
      this.datePickerStyle = {
        position: 'fixed',
        top: '-9999px',
        left: '-9999px',
        width: '0',
        height: '0',
        opacity: '0',
        pointerEvents: 'none'
      };
    },

    // 日期选择变化处理
    handleDateChange(value) {
       if (value && this.currentDayIconElement) {
        // 找到 day-control 的前一个兄弟元素（day-control）
        const insertDayElem = this.currentDayIconElement.previousElementSibling;
        if (insertDayElem && insertDayElem.classList.contains('insert-elem')) {
          // 将日期值加入到 day-control 中
          insertDayElem.textContent = value;
        }
      }
      this.hideDatePicker();
    },
    // 其他现有方法保持不变
    handleCurrentChange(val) {
       this.pageDto.pageNum = val
      this.pageAction()
    },

    searchAction() {
      this.pageAction()
    },

    pageAction() {
      this.loading = true;
      this.$sleep(500);
      api.pageRequest(this.pageDto).then(res => {
        if (200 === res.code) {
          this.tableData = res.data.list
          this.total = res.data.total
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    // showDialogAction(row) {
    //   this.detailInfoAction(row);
    //   if (row === null) {
    //     this.dialogFormVisible = true
    //   } else {
    //     this.dialogFormVisible = true
    //     this.form = {...row}
    //    }
    // },
    showDialogAction(row) {
      // 新标签页打开
      const routeData = this.$router.resolve({
        path: '/process/docdetail',
        query: { id: row.id }
      });
      window.open(routeData.href, '_blank');
    },



    handleClose(done) {
      this.$confirm('确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.pageAction()
        done()
      }).catch(() => {
      })
    },

    cancelAction() {
      this.$confirm('确认关闭？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.dialogFormVisible = false
        this.pageAction()
      }).catch(() => {
      })
    },

    detailInfoAction(row) {
      api.getTemplateData(row.templateCode).then(res => {
        if (200 === res.code) {
          this.loading = true
          let finalHtml = res.data.formTemplate;

          for (let key in res.data.formTemplateConfigMap) {
            finalHtml = this.processHtml(finalHtml, res.data.formTemplateConfigMap[key]);
          }

          this.contentHtml = finalHtml;
        }
        this.loading = false
      }).catch(() => {
        this.loading = false
      })
    },

    processHtml(html, config) {
       const parser = new DOMParser();
      const doc = parser.parseFromString(html, 'text/html');
      doc.querySelectorAll('span.edit-able.configured[data-control-key][data-control-type="1"]').forEach(field => field.remove());
      doc.querySelectorAll('span.edit-able.configured[data-control-key][data-control-type="2"]').forEach(field => field.remove());

      if (config.controlType === "1") {
        doc.querySelectorAll(`span.insert-elem[data-control-key="${config.controlKey}"][data-control-type="1"]`).forEach(field => {
          // 使用反引号 - 模板字符串生效
          field.setAttribute('data-control-isRequired', config.isRequired || false);
          field.setAttribute('contenteditable', config.isEdit);
          if (config.isEdit) {
            field.style.outline = 'none';
            field.style.border = 'none';
            field.style.borderBottom = '1px solid #000000';
            if (config.isUnderline) {
              field.style.borderBottom = '1px solid red';
            }
            field.style.backgroundColor = 'transparent';
          }
        });
      }
      if (config.controlType === "2") {
        doc.querySelectorAll(`span.day-control[data-control-key="${config.controlKey}"][data-control-type="2"]`).forEach(field => {
          if (config.isEdit) {
            // 创建新元素
            const newField = document.createElement('span');
            field.removeAttribute('data-mce-style');

            // 复制所有属性
            const attributes = field.attributes;
            for (let attr of attributes) {
              newField.setAttribute(attr.name, attr.value);
            }
            // 移除不需要的属性
            newField.removeAttribute('data-mce-style');
            newField.removeAttribute('cursor');
            // 移除 day-control 类，添加 insert-elem 类
            newField.classList.remove('day-control');
            newField.classList.add('insert-elem');
            // 移除所有背景相关样式
            newField.style.backgroundImage = 'none';
            newField.style.backgroundRepeat = 'no-repeat';
            newField.style.backgroundSize = 'auto';
            newField.style.backgroundPosition = 'initial';
            newField.style.padding = ''; // 同时移除padding

            // 在原元素前面插入新元素
            field.parentNode.insertBefore(newField, field);
            field.setAttribute('data-control-isRequired', config.isRequired || false);
          } else {
            field.remove();
          }
        });
      }
      return doc.body.innerHTML;
    },

    addAction() {
      this.loading = true;
      setTimeout(() => {
        // this.collectFieldData();
        this.collectFieldData2();
        // this.validateRequiredFields();
        console.info('dataMap：', {...this.dataMap});
        console.log(this.form)
        this.form.dataMap = {...this.dataMap}
        api.generatePdf(this.form).then(res => {
          if (200 === res.code) {
            console.log("请求成功文书地址：",res.data)
          }
          this.loading = false
        }).catch(() => {
          this.loading = false
        })
      }, 500);



    },
    collectFieldData2() {
      this.dataMap = {};
      if (this.$refs.contentContainer) {
        const editableFields = this.$refs.contentContainer.querySelectorAll('span.insert-elem[data-control-key]');
        editableFields.forEach(field => {
          const key = field.getAttribute('data-control-key');
          const value = field.textContent.trim();
          if (key) {
            this.dataMap[key] = value;
          }
        });
      }
    },
    collectFieldData() {
      this.dataMap = {};
      if (this.$refs.contentContainer) {
        const editableFields = this.$refs.contentContainer.querySelectorAll('span.insert-elem[data-control-key]');
        editableFields.forEach(field => {
          const key = field.getAttribute('data-control-key');
          const isRequired = field.getAttribute('data-control-isRequired');
          const controlType = field.getAttribute('data-control-type');
          const value = field.textContent.trim();
          if (key) {
            this.dataMap[key] = {
              value: value,
              isRequired: isRequired,
              controlType: controlType
              // element: field // 保存元素引用，便于后续操作
            };
          }
        });
      }
    },
    validateRequiredFields() {
      let hasError = false;
      if (this.$refs.contentContainer) {
        // 重置所有边框样式
        // const allFields = this.$refs.contentContainer.querySelectorAll('span.insert-elem');
        // allFields.forEach(field => {
        //   field.style.border = '';
        //   field.style.borderBottom = '';
        // });

        // 检查每个字段
        for (let key in this.dataMap) {
          const fieldConfig = {...this.dataMap[key]};
          console.log(`字段:${key}, 是否必填:${fieldConfig.isRequired}, 值:"${fieldConfig.value}"`);
          console.log(`字段 ${key} 是否为空:`, isEmpty);

          // 更全面的空值检查
          const isEmpty = !fieldConfig.value ||
            fieldConfig.value === '' ||
            fieldConfig.value === null ||
            fieldConfig.value === undefined ||
            fieldConfig.value === 'null' ||
            fieldConfig.value === 'undefined';
          // 如果字段是必填且值为空
          if (fieldConfig.isRequired && isEmpty) {
            // 找到对应的 DOM 元素
              const fieldElement = this.$refs.contentContainer.querySelector(`span.insert-elem[data-control-key="${key}"]`);
              if (fieldElement) {
                // 添加红色边框
                fieldElement.style.border = '2px solid red';
                hasError = true;
                console.warn(`🚨 必填字段 ${key} 为空，已标记红色边框`);
              }
          }
        }
      }
      console.log('最终验证结果 - 是否有错误:', hasError);

      if (hasError) {
        this.$message.error('请填写所有必填字段');
        return false;
      }
      return true;
    }



  }
}
</script>

<style lang="scss" scoped>
.app-container {
  position: relative;
}

.drawer-content {
  display: flex;
  flex-direction: row;
  height: 100vh;
  padding: 10px 10px 110px 10px;
  background: #f5f7fa;
}

.drawer-content-left {
  width: 60%;
}

.drawer-content-right {
  width: 40%;
  background: #FFFFFF;
  padding: 10px 50px;
  flex: 1;
  overflow-y: auto;
  min-height: 0;

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: #f1f1f1;
  }

  &::-webkit-scrollbar-thumb {
    background: #c1c1c1;
  }
}

.drawer-body {
  position: relative;
}

.drawer-header {
  padding: 12px 30px;
  text-align: left;
  border-bottom: 1px solid #DDDDDD;
  background: #fff;
  position: sticky;
  bottom: 0;
  font-size: 20px;
  font-family: SimHei;
}

.drawer-footer {
  padding: 8px 30px;
  text-align: center;
  border-top: 1px solid #DDDDDD;
  background: #fff;
  position: sticky;
  bottom: 0;
}

/* 隐藏的日期选择器 */
:deep(.hidden-date-picker) {
  position: fixed !important;
  top: 0 !important;
  left: 0 !important;
  width: 0 !important;
  height: 0 !important;
  overflow: hidden !important;
  opacity: 0 !important;
  pointer-events: none !important;
}

:deep(.hidden-date-picker .el-input__inner) {
  display: none !important;
}

table, tr, td, th {
  margin: 0 !important;
  padding: 0 !important;
}

</style>

